package io.renren.wechat.service;

import io.renren.wechat.common.aes.SHA1;
import io.renren.wechat.support.MessageDigestUtils;
import io.renren.wechat.support.WXPayUtil;
import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author dmcp@qq.com
 * @since 2021/12/2 21:56
 */

@Component
public class SignService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SignService.class);
    private static final String ENCRYPTED_STR_FORMAT = "jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s";

    /**
     * jsapi_ticket=JSAPI_TICKET&noncestr=NONCESTR&timestamp=TIMESTAMP&url=URL
     *
     * @param requestUrl 签名用的url必须是调用JS接口页面的完整URL。
     * @param timestamp  当前时间戳，精确到秒
     * @param nonce      随机串
     * @param ticket     jsapi ticket
     * @return signature
     */
    public String sign(String requestUrl, String timestamp, String nonce, String ticket) {
        String plainText = String.format(ENCRYPTED_STR_FORMAT, ticket, nonce, timestamp, requestUrl);
        // LOGGER.debug("before calc sha1 str: {}", plainText);

        final String shaValue = sha(plainText);
        // LOGGER.debug("after calc sha1 str: {}", shaValue);

        return shaValue;
    }

    public String sha(String plainText) {
        try {
            MessageDigest sha = MessageDigestUtils.getDigest("SHA");
            final byte[] cipherBytes = sha.digest(plainText.getBytes(StandardCharsets.UTF_8));

            return Hex.encodeHexString(cipherBytes);
        } catch (Exception e) {
            LOGGER.error("sha failed", e);

            throw new RuntimeException(e);
        }
    }

    public String sha1(String plainText) {
        try {
            return SHA1.getSHA1(plainText);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("sha1 failed", e);
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        SignService signService = new SignService();

        String ticket = "CwY1nPYp5kpisFbPm+n3JQ==";
        // String url = "https://www.zijisz.com/h5/dmcp/dmcp.html";
        // String url = "https://www.zijisz.com/h5/dmcp/test.html";
        String url = "https://www.zijisz.com/scan_test/";


        // String ticket = "zYlCpkk3UFQVz/31RlPZPQ==";
        // String url = "https://www.zijisz.com/h5/dmcp/other.html";


        String timestamp = String.valueOf(WXPayUtil.getCurrentTimestamp());
        String nonce = WXPayUtil.generateNonceStr();
        System.out.println("\n\n\ttimestamp: " + timestamp + ",");
        System.out.println("\tnonceStr: '" + nonce + "',");
        final String sign = signService.sign(url, timestamp, nonce, ticket);
        System.out.println("\tsignature: '" + sign + "',\n\n");
    }

}
